<?php

namespace app\zyhsapi\controller\v3;

use app\astro\controller\Data;
use app\common\lib\astrolog\SynastryData;
use app\common\lib\exception\ApiException;
use app\common\model\HeSijiaoText;
use app\common\model\HeText;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsRecode;
use app\zyhsapi\model\ZyhsSynastryResult;
use think\Env;
use think\response\Json;

class Synastry extends ZyhsAuth
{
    /**
     * @var array
     */
    private $settting = [
        'asp_orb_all' => [0 => 6, 60 => 4, 90 => 6, 120 => 6, 180 => 6, 30 => 1, 150 => 2, 45 => 2, 135 => 2, 72 => 2, 144 => 2],
        'asps_display' => [0 => 0, 1 => 60, 2 => 90, 3 => 120, 4 => 180],
        'planets_display' => '111111111100100001001',
        'planet_orb_all' => [0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0,],
        'h_sys' => 'p',
    ];

    /**
     * 获取合盘记录
     * @return Json
     * @throws \Exception
     */
    public function getHistoryList()
    {
        $page = input('page/d', 1);

        $uid = (int)$this->user['id'];

        $data = (new ZyhsSynastryResult())->getUserList($uid, $page);

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 查看合盘结果
     * @return Json
     */
    public function getWithScore()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);
        $rid1 = input('rid1/d', 0);
        $rid2 = input('rid2/d', 0);
        $uid = (int)$this->user['id'];
        $synastryType = 1; //合盘类型 1=>普通合盘 2=>明星合盘 5=>名人合盘  6=>邀请好友填档案合盘（不添加档案）

        if (!in_array($type, [1, 2], true) || ($type === 1 && !$id) || ($type !== 1 && (!$rid1 || !$rid2)))
        {
            return show(config('code.error'), '请求异常');
        }

        $recodeModel = new ZyhsRecode();
        $saveData = [];
        // 通过id查询
        if ($type === 1)
        {
            $result = (new ZyhsSynastryResult())->getInfoById($id);
            if (!$result || $result['uid'] != $uid)
            {
                return show(config('code.error'), '数据不存在');
            }
            if (isset($result['type']))
            {
                $synastryType = (int)$result['type'];
            }

            $records = json_decode($result['extra'], true);
            $rid1 = (int)$result['rid1'];
            $rid2 = (int)$result['rid2'];
            // 获取完整合盘数据
            $records['type'] = 1;

            if (!in_array($synastryType, [5, 6], true) && (!$rid1 || !$rid2))
            {   // 不显示 合盘报告
                $synastryType = 2;
            }
        } else
        {
            $record1 = $recodeModel->getInfoById($rid1, ['id', 'uid', 'name', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'avatar', 'is_summer', 'isself', 'sun', 'moon', 'asc']);

            if (!$record1 || $record1['uid'] != $uid)
            {
                return show(config('code.error'), '档案缺失');
            }
            if ($record1['isself'] == 1)
            {
                $record1['name_old'] = $record1['name'];
                $record1['name'] = '自己';
            }

            $record2 = $recodeModel->getInfoById($rid2, ['id', 'uid', 'name', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'avatar', 'is_summer', 'isself']);
            if (!$record2 || $record2['uid'] != $uid)
            {
                return show(config('code.error'), '档案缺失');
            }

            if ($record2['isself'] == 1)
            {
                $record2['name'] = '自己';
            }

            $records = [
                'recode1' => $record1,
                'recode2' => $record2,
                'type' => 1,
            ];

            //rid处理确保入库唯一性
            if ($rid2 > $rid1)
            {
                $newRid1 = $rid2;
                $newRid2 = $rid1;
            } else
            {
                $newRid1 = $rid1;
                $newRid2 = $rid2;
            }

            $saveData = [ // 合盘记录表
                'uid' => $uid,
                'type' => $synastryType,
                'create_type' => 2,
                'rid1' => $newRid1,
                'rid2' => $newRid2,
                'create_time' => $this->request->time(),
                'update_time' => $this->request->time(),
                'nickname1' => $record1['name'],
                'nickname2' => $record2['name'],
                'avatar1' => $record1['avatar'] ?: '',
                'avatar2' => $record2['avatar'] ?: '',
                'extra' => json_encode([
                    'recode1' => $record1,
                    'recode2' => $record2,
                ]),
            ];
        }

        $data = (new SynastryData())->setSynastryType($synastryType)->getScore($records);

        if ($saveData)
        {
            $score = 0;
            foreach ($data['score'] as $item)
            {
                $score += $item['num'];
            }
            $saveData['score'] = $score;// 总分
            $saveData['relation'] = $data['relation'][0]['name_cn']; // 双方可能的关系
            // 去写入
            $id = (new ZyhsSynastryResult())->saveData($saveData);
        }

        $data['nickname1'] = $records['recode1']['name'];
        $data['nickname2'] = $records['recode2']['name'];
        $data['avatar1'] = $records['recode1']['avatar'];
        $data['avatar2'] = $records['recode2']['avatar'];
        $data['rid1'] = $rid1;
        $data['rid2'] = $rid2;
        $data['type'] = in_array($synastryType, [1, 5, 6], true) ? $synastryType : 2; // 1显示合盘 2不显示   5=>名人合盘  6=>邀请好友合盘（不添加档案）
        $data['id'] = (int)$id;


        $oss = Env::get('host.photo');

        $data['btn_list'] = [
            [
                'name' => '详细解读',
                'target' => 'local',
                'link' => "synastry_result_explain?id={$id}&need_auth=1",
                'tip_icon' => '',
            ], [
                'name' => '咨询师解答',
                'target' => 'local',
                'link' => "consult_astr_ask?need_auth=2",
                'tip_icon' => $oss . '/zyhsapp/synastry/synastry_new.png',
            ],
        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 合盘详细解读
     * @return Json
     * @throws ApiException
     */
    public function getHeScore()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }
        $uid = $this->user['id'];

        $result = (new ZyhsSynastryResult())->getInfoById($id);
        if ($result['uid'] != $uid)
        {
            return show(config('code.error'), '数据不存在');
        }

        $records = json_decode($result['extra'], true);

        $Data = new Data();
        // 使用固定配置
        $Data->planets_display = '111111111100000001111';
        $Data->asps_display = $this->settting['asps_display'];
        $Data->asp_orb_all = $this->settting['asp_orb_all'];
        $Data->planet_orb_all = $this->settting['planet_orb_all'];

        $userinfo1 = $records['recode1'];

        $timestamp1 = $Data->deal_time($userinfo1);
        $utdatenow1 = strftime('%d.%m.%Y', $timestamp1);
        $utnow1 = strftime('%H:%M:%S', $timestamp1);
        $longitude1 = ($userinfo1['long_deg'] + $userinfo1['long_min'] / 60) * $userinfo1['ew'];
        $latitude1 = ($userinfo1['lat_deg'] + $userinfo1['lat_min'] / 60) * $userinfo1['ns'];


        $userinfo2 = $records['recode2'];
        $timestamp2 = $Data->deal_time($userinfo2);
        $utdatenow2 = strftime('%d.%m.%Y', $timestamp2);
        $utnow2 = strftime('%H:%M:%S', $timestamp2);
        $longitude2 = ($userinfo2['long_deg'] + $userinfo2['long_min'] / 60) * $userinfo2['ew'];
        $latitude2 = ($userinfo2['lat_deg'] + $userinfo2['lat_min'] / 60) * $userinfo2['ns'];

        $options1 = ['utdatenow' => $utdatenow1, 'utnow' => $utnow1, 'longitude' => $longitude1, 'latitude' => $latitude1, 'h_sys' => $this->settting['h_sys']];
        $options2 = ['utdatenow' => $utdatenow2, 'utnow' => $utnow2, 'longitude' => $longitude2, 'latitude' => $latitude2, 'h_sys' => $this->settting['h_sys']];

        $out1 = $Data->execData($options1);
        $out2 = $Data->execData($options2);

        $original_data1 = $Data->getOriginalData($out1);
        $original_data2 = $Data->getOriginalData($out2);
        $Data->array_remove($original_data1, $Data->planets_display);
        $Data->array_remove($original_data2, $Data->planets_display);

        $phase1 = $Data->planetPkPlanet($original_data1, $original_data2);
        $phase2 = $Data->planetPkPlanet($original_data2, $original_data1);

        $text_data = [
            'a_vs_b' => [],
            'b_vs_a' => [],
        ];

        $HeTextModel = new HeText();
        $HeSijiaoTextModel = new HeSijiaoText();
        //缓存,获取所有合盘相位词条
        $he_text = $HeTextModel->getHeText();
        //缓存,获取所有合轴词条
        $he_sijao_text = $HeSijiaoTextModel->getHeSijiaoText();

        if (!empty($phase1['phase']))
        {
            foreach ($phase1['phase'] as $ps)
            {
                $data_1 = null;
                $phase_deg = $ps['phase_deg'];
                $ke = $ps['id1'] . '-' . $ps['id2'];
                $map['planet'] = $ke;
                $map['phase'] = '';
                if (in_array($phase_deg, [0, 60, 90, 120, 180]))
                {
                    if ($phase_deg == 0)
                    {
                        $map['phase'] = '合';
                    } elseif ($phase_deg == 60 || $phase_deg == 120)
                    {
                        $map['phase'] = '拱/六分';
                    } elseif ($phase_deg == 90)
                    {
                        $map['phase'] = '刑';
                    } elseif ($phase_deg == 180)
                    {
                        $map['phase'] = '冲';
                    }
                }
                $key = $ke . '-' . $map['phase'];

                if (isset($he_text[$key])) $data_1 = $he_text[$key];

                elseif ($phase_deg == 0 && isset($he_sijao_text[$ke])) $data_1 = $he_sijao_text[$ke];

                if ($data_1 !== NULL)
                {
                    $text_data['a_vs_b'][] = [
                        'phase' => $phase_deg,
                        'text' => $data_1['text'],
                        'good' => -1,
                        'love' => 0,
                        'id1' => $ps['id1'],
                        'id2' => $ps['id2'],
                    ];
                }

            }
        }
        if (!empty($phase2['phase']))
        {
            foreach ($phase2['phase'] as $ps)
            {
                $data_2 = null;
                if ($ps['id1'] == $ps['id2']) continue;
                $phase_deg = $ps['phase_deg'];
                $ke = $ps['id1'] . '-' . $ps['id2'];
                $map['planet'] = $ke;
                if (in_array($phase_deg, [0, 60, 90, 120, 180]))
                {
                    if ($phase_deg == 0)
                    {
                        $map['phase'] = '合';
                    } elseif ($phase_deg == 60 || $phase_deg == 120)
                    {
                        $map['phase'] = '拱/六分';
                    } elseif ($phase_deg == 90)
                    {
                        $map['phase'] = '刑';
                    } elseif ($phase_deg == 180)
                    {
                        $map['phase'] = '冲';
                    }
                }
                $key = $ke . '-' . $map['phase'];

                if (isset($he_text[$key])) $data_2 = $he_text[$key];

                elseif ($phase_deg == 0 && isset($he_sijao_text[$ke])) $data_2 = $he_sijao_text[$ke];

                if ($data_2 !== NULL)
                {
                    $text_data['b_vs_a'][] = [
                        'phase' => $phase_deg,
                        'text' => $data_2['text'],
                        'good' => -1,
                        'love' => 0,
                        'id1' => $ps['id1'],
                        'id2' => $ps['id2'],
                    ];
                }
            }
        }
        if ($userinfo1['isself'] == 1) $userinfo1['name'] = '你';
        if (isset($userinfo2['isself']) && $userinfo2['isself'] == 1) $userinfo2['name'] = '你';
        foreach ($text_data as $ab => $text_data_ab)
        {
            foreach ($text_data_ab as $k => $dd)
            {
                $text = $dd['text'];
                if ($dd['id1'] == 0)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【太阳方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【太阳方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 0)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【太阳方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【太阳方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 1)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【月亮方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【月亮方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 1)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【月亮方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【月亮方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 2)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【水星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【水星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 2)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【水星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【水星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 3)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【金星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【金星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 3)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【金星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【金星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 4)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【火星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【火星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 4)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【火星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【火星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 5)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【木星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【木星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 5)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【木星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【木星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 6)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【土星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【土星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 6)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【土星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【土星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 7)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【天王星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【天王星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 7)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【天王星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【天王星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 8)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【海王星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【海王星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 8)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【海王星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【海王星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == 9)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【冥王星方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【冥王星方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == 9)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【冥王星方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【冥王星方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == ASC)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【上升方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【上升方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == ASC)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【上升方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【上升方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == IC)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【天底方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【天底方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == IC)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【天底方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【天底方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == DES)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【下降方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【下降方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == DES)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【下降方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【下降方】', $userinfo1['name'], $text);
                    }
                }

                if ($dd['id1'] == MC)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【天顶方】', $userinfo1['name'], $text);
                    } else
                    {
                        $text = str_replace('【天顶方】', $userinfo2['name'], $text);
                    }
                }
                if ($dd['id2'] == MC)
                {
                    if ($ab == 'a_vs_b')
                    {
                        $text = str_replace('【天顶方】', $userinfo2['name'], $text);
                    } else
                    {
                        $text = str_replace('【天顶方】', $userinfo1['name'], $text);
                    }
                }

                $text = str_replace('ta' . $userinfo1['name'], 'ta', $text);
                $text = str_replace('ta' . $userinfo2['name'], 'ta', $text);

                $text_data[$ab][$k]['text'] = $text;

                $id1_id2 = $dd['id1'] . '-' . $dd['id2'];
                // 是否为桃花相位
                if (
                    ($id1_id2 == '3-4')
                    || ($dd['phase'] != 90 && $id1_id2 == '1-4')
                    || ($dd['phase'] != 90 && $id1_id2 == '0-1')
                    || (in_array($dd['phase'], [0, 60, 120]) && $id1_id2 == '1-1')
                    || (in_array($dd['phase'], [0, 60, 120]) && $id1_id2 == '1-3')
                    || (in_array($dd['phase'], [0, 60, 120]) && $id1_id2 == '0-3')
                    || ($dd['phase'] == 0 && ($id1_id2 == '1-' . ASC || $id1_id2 == '1-' . DES))
                    || ($dd['phase'] == 0 && ($id1_id2 == '3-' . ASC || $id1_id2 == '3-' . DES))
                )
                {
                    $text_data[$ab][$k]['love'] = 1;
                }
                // 相位 有利
                if (
                    in_array($dd['phase'], [60, 120])
                    ||
                    (
                        $dd['phase'] == 0 && $dd['id1'] != 4 && $dd['id1'] != 6 && $dd['id2'] != 4 && $dd['id2'] != 6
                    )
                    ||
                    (
                        $dd['phase'] == 0
                        &&
                        (
                            (in_array($dd['id1'], [0, 1, 2, 3, 5]) && in_array($dd['id2'], [ASC, IC, DES, MC]))
                            || (in_array($dd['id2'], [0, 1, 2, 3, 5]) && in_array($dd['id1'], [ASC, IC, DES, MC]))
                        )
                    )
                )
                {
                    $text_data[$ab][$k]['good'] = 1;
                }
                // 相位  中性
                if (
                    (
                        $dd['phase'] == 180 && $dd['id1'] != 4 && $dd['id1'] != 6 && $dd['id2'] != 4 && $dd['id2'] != 6
                    )
                    ||
                    (
                        $dd['phase'] == 0 && ($dd['id1'] == 4 || $dd['id1'] == 6 || $dd['id2'] == 4 || $dd['id2'] == 6)
                    )
                    ||
                    (
                        $dd['phase'] == 0
                        &&
                        (
                            (in_array($dd['id1'], [4, 6]) && $dd['id2'] > 16)
                            || (in_array($dd['id2'], [4, 6]) && $dd['id1'] > 16)
                        )
                    )
                    ||
                    (
                        $dd['phase'] == 180 && (($dd['id1'] == 4 && $dd['id2'] == 3) || ($dd['id2'] == 4 && $dd['id1'] == 3))
                    )
                    ||
                    (
                        $dd['phase'] == 90
                        &&
                        (
                            ($dd['id1'] == 5 && in_array($dd['id2'], [0, 1, 3]))
                            || ($dd['id2'] == 5 && in_array($dd['id1'], [0, 1, 3]))
                        )
                    )
                )
                {
                    $text_data[$ab][$k]['good'] = 0;
                }
            }
        }

        $text_data['name_a'] = $records['recode1']['name'];
        $text_data['name_b'] = $records['recode2']['name'];

        return show(config('code.success'), '请求成功', $text_data);
    }

    /**
     * 删除合盘记录
     * @return Json
     * @throws \Exception
     */
    public function delHistory()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '数据不存在');
        }
        $zyhsSynastryResultModel = new ZyhsSynastryResult();
        $result = $zyhsSynastryResultModel->getInfoById($id);
        if (!$result || $result['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '数据不存在');
        }
        $res = $zyhsSynastryResultModel->delData($this->user['id'], $id);

        if ($res === true)
        {
            return show(config('code.success'), '操作成功');
        }
        return show(config('code.error'), '操作失败');
    }
}